package com.cheung.leetcode.arr;

import  org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.arr
 * @Author :  cheungming
 * @CreateTime : 2024-07-14 21:02:58
 * @Description : 数组
 * @Version : 1.0
 */
public class Code169Test {
    public int majorityElement(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() > nums.length / 2) {
                return entry.getKey();
            }
        }
        return 0;
    }

    @Test
    public void test1() {
        int[] nums = {3, 2, 3};
        assert 3 == majorityElement(nums);
    }

    @Test
    public void test2() {
        int[] nums = {2, 2, 1, 1, 1, 2, 2};
        assert 2 == majorityElement(nums);
    }
}
